/*
 * File: SendThankYous.java Author: Robert Bittle <guywithnose@gmail.com>
 */
package servlets.cron;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import data.JavaCurl;

import faceBook.Message;
import faceBook.User;

/**
 * The Class SendThankYous.
 */
public class SendThankYous extends HttpServlet
{

  /*
   * (non-Javadoc)
   * 
   * @see
   * javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest,
   * javax.servlet.http.HttpServletResponse)
   */
  @Override
  @SuppressWarnings("unused")
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException
  {
    ArrayList<User> liveUsers = User.getAllActiveUsers();
    for (User me : liveUsers)
    {
      if (me.getBirthday() != null)
      {
        Calendar today = new GregorianCalendar();
        today.add(Calendar.DATE, -1);
        GregorianCalendar birthday = new GregorianCalendar();
        birthday.setTimeInMillis(me.getBirthday().getTime());
        int bDate = birthday.get(Calendar.DATE);
        int tDate = today.get(Calendar.DATE);
        int bMonth = birthday.get(Calendar.MONTH);
        int tMonth = today.get(Calendar.MONTH);
        // I'm using the reply feature and it's my birthday
        if (me.getUseReply()
            && birthday.get(Calendar.DATE) == today.get(Calendar.DATE)
            && birthday.get(Calendar.MONTH) == today.get(Calendar.MONTH))
        {
          String url = "https://graph.facebook.com/me/feed?access_token="
              + me.getAccessToken();

          // get wall posts
          JSONObject jo = new JSONObject();
          JSONArray listOfPosts = new JSONArray();
          long now = today.getTimeInMillis();
          do
          {
            String response = JavaCurl.getUrl(url);

            try
            {
              jo = new JSONObject(response);
              listOfPosts = (JSONArray) jo.get("data");

              for (int i = 0; i < listOfPosts.length(); i++)
              {
                JSONObject wallPost = listOfPosts.getJSONObject(i);
                String date = wallPost.getString("updated_time");

                date = date.split(":")[0];

                String[] dateParts = date.split("[-T]");
                Calendar postDate = new GregorianCalendar(
                    Integer.valueOf(dateParts[0]),
                    Integer.valueOf(dateParts[1]) - 1,
                    Integer.valueOf(dateParts[2]));

                if (postDate.getTimeInMillis() - now > 172800000)// two days
                  break;

                if (isBirthdayMessage(wallPost))
                  replyThankYou(me, wallPost);
              }

              if (jo.has("paging"))
                url = jo.getJSONObject("paging").getString("next");

            } catch (JSONException e)
            {
              e.printStackTrace();
            }

          } while (jo.has("paging") && listOfPosts.length() > 0);
        }
      }
    }

  }

  /**
   * Checks if is birthday message.
   * 
   * @param post
   *          the post
   * @return true, if is birthday message
   */
  private static boolean isBirthdayMessage(JSONObject post)
  {
    if (!(post.has("from") && post.has("to")) || !post.has("message"))
      return false;
    try
    {
      String message = post.getString("message").toLowerCase();
      if (message.contains("happy") && message.contains("birthday")
          && !message.contains("thanks"))
        return true;

    } catch (JSONException e)
    {
      e.printStackTrace();
    }

    return false;
  }

  /**
   * Reply thank you.
   * 
   * @param me
   *          the me
   * @param post
   *          the post
   */
  private static void replyThankYou(User me, JSONObject post)
  {
    Message tym = new Message();
    try
    {
      User friend = new User(post.getJSONObject("from").getLong("id"));
      friend.save();
      tym.addFriend(friend);

      try
      {
        String id = post.getString("id");
        if (!Message.postHasComment(id))
        {
          tym.setUser(me);
          tym.setCommentOn(id);

          if (me.getReplyMessage() != null)
            tym.setMessage(me.replaceString(me.getReplyMessage()));
          else
            tym.setMessage("Thanks for the Happy Birthday!");

          tym.setLink("");

          tym.postComment();
        }
      } catch (JSONException e)
      {
        // Not a valid Message
      }
    } catch (JSONException e)
    {
      // Not a valid Message
    }
  }
}
